import React, { useState, useEffect, useRef, useCallback } from 'react';
import { fix1 } from 'utils';

// css/config.scss
// $no-break: 0;
// $sm-break: 480px;
// $md-break: 768px;
// $lg-break: 1024px;
// $xl-break: 1440px;

export const BREAKPOINTS = {
    SM: '480px',
    MD: '768px',
    LG: '1024px',
    XL: '1440px',
};

const MDQuery = `(min-width: ${BREAKPOINTS.SM})`;
const LGQuery = `(min-width: ${BREAKPOINTS.MD})`;
const XLQuery = `(min-width: ${BREAKPOINTS.LG})`;
const XXLQuery = `(min-width: ${BREAKPOINTS.XL})`;

export const useMediaQuery = (query: string) => {
    const getMatches = (query: string): boolean => {
        // Prevents SSR issues
        if (typeof window !== 'undefined') {
            return window.matchMedia(query).matches;
        }
        return false;
    };

    const [matches, setMatches] = useState<boolean>(getMatches(query));

    function handleChange() {
        setMatches(getMatches(query));
    }

    useEffect(() => {
        const matchMedia = window.matchMedia(query);

        // Triggered at the first client-side load and if query changes
        handleChange();

        // Listen matchMedia
        if (matchMedia.addListener) {
            matchMedia.addListener(handleChange);
        } else {
            matchMedia.addEventListener('change', handleChange);
        }

        return () => {
            if (matchMedia.removeListener) {
                matchMedia.removeListener(handleChange);
            } else {
                matchMedia.removeEventListener('change', handleChange);
            }
        };
    }, [query]);

    return matches;
};

export const useIsSMScreen = () => {
    return !useMediaQuery(MDQuery);
};

export const useIsMDScreen = () => {
    return useMediaQuery(MDQuery);
};

export const useIsLGScreen = () => {
    return useMediaQuery(LGQuery);
};

export const useIsXLScreen = () => {
    return useMediaQuery(XLQuery);
};

export const useIsXXLScreen = () => {
    return useMediaQuery(XXLQuery);
};

export const useBreakPoint = () => {
    const isSMScreen = useIsSMScreen();
    const isMDScreen = useIsMDScreen();
    const isLGScren = useIsLGScreen();
    const isXLScreen = useIsXLScreen();
    const isXXLScreen = useIsXXLScreen();

    if (isXXLScreen) {
        return 'XXL';
    } else if (isXLScreen) {
        return 'XL';
    } else if (isLGScren) {
        return 'LG';
    } else if (isMDScreen) {
        return 'MD';
    } else if (isSMScreen) {
        return 'SM';
    }
};

export const useEffectSkipFirstRender = (fn, args) => {
    const firstRenderRef = React.useRef(true);

    useEffect(() => {
        if (firstRenderRef.current) {
            firstRenderRef.current = false;
        } else {
            fn?.();
        }
    }, args);
};

export const useCounter = ({ min, max, intervalTime, autoStart = true, step = 0.1, repeat = true }) => {
    const [num, setNum] = React.useState(min);
    const [interval, setIntervalState] = React.useState<number>();
    const [isRunning, setIsRunning] = React.useState(autoStart);

    useEffect(() => {
        if (autoStart) {
            start();
            setIsRunning(true);
        }

        return () => {
            clearInterval(interval);
            setIntervalState(null);
        };
    }, [min, max]);

    function stop() {
        interval && clearInterval(interval);
        setIntervalState(null);
        setIsRunning(false);
    }

    function start() {
        interval && clearInterval(interval);

        const i = setInterval(() => {
            setNum((prevNum) => {
                if (prevNum < max) {
                    return fix1(prevNum + step);
                } else {
                    if (repeat) {
                        return fix1(min);
                    } else {
                        return prevNum;
                    }
                }
            });
        }, intervalTime);

        setIntervalState(i);
        setIsRunning(true);
    }

    return { start, stop, isRunning, num };
};

export const useRandomNum = ({ min, max, intervalTime, autoStart = true }) => {
    const [num, setNum] = React.useState(min);
    const [interval, setIntervalState] = React.useState<number>();
    const [isRunning, setIsRunning] = React.useState(autoStart);

    useEffect(() => {
        if (autoStart) {
            start();
            setIsRunning(true);
        }

        return () => {
            clearInterval(interval);
            setIntervalState(null);
        };
    }, [min, max]);

    function stop() {
        interval && clearInterval(interval);
        setIntervalState(null);
        setIsRunning(false);
    }

    function start() {
        interval && clearInterval(interval);

        const newInterval = setInterval(() => {
            const newNum = min + Math.random() * (max - min);
            setNum(newNum.toFixed(1));
        }, intervalTime);

        setIntervalState(newInterval);
        setIsRunning(true);
    }

    return { start, stop, isRunning, num };
};

export const useInjectRemovableCSS = (cssLink) => {
    useEffect(() => {
        const cacheBuster = ''; // `?v=${~~(Math.random()*0xFFFFFF)}`;
        const css = cssLink + cacheBuster;
        let injectedStyle = document.getElementById('injected');
        if (!injectedStyle) {
            injectedStyle = document.createElement('link') as HTMLLinkElement;
            injectedStyle.type = 'text/css';
            injectedStyle.rel = 'stylesheet';
            injectedStyle.id = 'injected';
            document.head.append(injectedStyle);
        }
        injectedStyle.setAttribute('href', css);
        injectedStyle.removeAttribute('disabled');

        return () => {
            injectedStyle.setAttribute('disabled', 'true');
        };
    }, []);
};

export const isZH = (lang) => {
    return lang.includes('zh');
};


